import React from 'react';
import { Icon } from 'antd';
import styles from './index.module.less';

export default function RateBar(props) {
    const { audio, rates = [0.4, 0.6, 0.8, 1, 1.2, 1.5, 2, 2.5, 3], defaultRate = 1 } = props;

    const [nowIndex, setNowIndex] = React.useState(rates.indexOf(defaultRate) !== -1 ? rates.indexOf(defaultRate) : 0);

    const handleRate = r => {
        const newIndex = nowIndex + r;
        if (newIndex > rates.length - 1 || newIndex < 0) {
            return;
        }
        setNowIndex(newIndex);
        audio.playbackRate = rates[newIndex];
    };

    React.useEffect(() => {
        if (defaultRate === 1 && rates.indexOf(defaultRate) !== -1) {
            return;
        }
        audio.playbackRate = rates[nowIndex];
    }, [rates, defaultRate]);

    return (
        <div className={styles.rateBarWrap}>
            <Icon
                type="backward"
                style={{ fontSize: 20, marginLeft: 10, marginRight: 10 }}
                onClick={() => handleRate(-1)}
            />
            <div>{rates[nowIndex].toFixed(1)}</div>
            <Icon
                type="forward"
                style={{ fontSize: 20, marginLeft: 10, marginRight: 10 }}
                onClick={() => handleRate(1)}
            />
        </div>
    );
}
